package info.techgeek.labs.java5Features.thread.blockingqueue;

import java.util.concurrent.*;

public class Server extends Thread {

	static final int CAPACITY = 2;
	private BlockingQueue<Request> queue = new LinkedBlockingQueue<Request>(CAPACITY);

	public void accept(Request request, int index) {
		System.out.println("Server accept request = "+request);
		try {
			System.out.println("Server accept index "+index);
			queue.put(request);
			System.out.println(">>>>>>>>>>> queue.size(); "+queue.size());
			
		} catch (InterruptedException e) {
			throw new RuntimeException("add to queue interrupted");
		}
	}

	public void run() {
		System.out.println("Server run");
		while (true){
//			try {
				System.out.println(" queue.size(); "+queue.size());
				execute(queue.peek());
//			} catch (InterruptedException e) {
//			}
		}
	}

	private void execute(final Request request) {
		System.out.println("Server execute "+request);
		new Thread(new Runnable() {
			public void run() {
				request.execute();
			}
		}).start();
	}
	
}

